#pragma once
#include "Socket.hpp"
#include <poll.h>
#include <sys/time.h>
using namespace std;
static const uint16_t defaultport = 8080;
static const int fd_num_max = 64;
int defaultfd = -1;
int non_event = 0;
class PollServer
{
public:
    PollServer(uint16_t port = defaultport) : _port(port)
    {
        for (int i = 0; i < fd_num_max; i++)
        {
            _event_fds[i].fd = defaultfd;
            _event_fds[i].events = non_event;
            _event_fds[i].revents = non_event;
            // cout << "fd_array[" << i << "]" << ": " << fd_array[i] << endl;
        }
    }
    bool Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
        return true;
    }
    void Accepter()
    {
        std::string clientip;
        uint16_t clientport = 0;
        int sock = _listensock.Accept(&clientip, &clientport);
        if (sock < 0)
            return;
        log(Info, "Accept Success, %s:%d, fd: %d", clientip.c_str(), clientport, sock);
        int pos = 1;
        for (; pos < fd_num_max; pos++)
        {
            if (_event_fds[pos].fd != defaultfd)
                continue;
            else
                break;
        }
        if (pos == fd_num_max)
        {
            log(Warning, "server is full,close %d now!", sock);
            close(sock);
            //扩容
        }
        else
        {
            _event_fds[pos].fd = sock; 
            _event_fds[pos].events = POLLIN;
            _event_fds[pos].revents = non_event;           
            PrintFd();
            // todo
        }
    }
    void Recver(int fd, int pos)
    {
        // demo读取
        char buffer[1024];
        size_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "Get a message: " << buffer << endl;
        }
        else if (n == 0) // 对方将读fd关闭
        {
            log(Info, "client quit,me too,close fd is: ", fd);
            close(fd);
            _event_fds[pos].fd = defaultfd; // 从select中移除
        }
        else
        {
            log(Warning, "recv error,close fd is: ", fd);
            close(fd);
            _event_fds[pos].fd = defaultfd; // 从select中移除
        }
    }
    void Dispatcher() // 事件派发器
    {
        for (int i = 0; i < fd_num_max; i++)
        {
            int fd = _event_fds[i].fd;
            if (fd == defaultfd)
                continue;
            if (_event_fds->revents & POLLIN)
            {
                // 链接事件,获取新链接
                if (fd == _listensock.Fd())
                {
                    Accepter(); // 链接管理器
                }
                else // 非listensock
                {
                    Recver(fd, i);
                }
            }
        }
    }
    void Start()
    {
        _event_fds[0].fd = _listensock.Fd();
        _event_fds[0].events = POLLIN;
        int timeout = 3000; //3s
        while (true)
        {
            int n = poll(_event_fds,fd_num_max,timeout);
            switch (n)
            {
            case 0:
                cout << "time out..." <<endl;
                break;
            case -1:
                cerr << "poll error" << endl;
                break;
            default:
                // 有事件已经就绪
                // 上层如果不及时将事件取走，否则select一直通知你
                cout << "get a new link" << endl;
                Dispatcher();
                break;
            }
        }
    }
    void PrintFd()
    {
        cout << "online fd list: ";
        for (int i = 0; i < fd_num_max; i++)
        {
            if (_event_fds->fd == defaultfd)
                continue;
            cout << _event_fds->fd << " ";
        }
        cout << endl;
    }
    ~PollServer()
    {
        _listensock.Close();
    }

private:
    MySocket _listensock;
    uint16_t _port;
    struct pollfd _event_fds[fd_num_max];
};
